import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;//这里的时间,通过毫秒级时间戳
    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }
    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    public int compareTo(MyTimerTask o) {
        //此处这里的-的顺序,就决定了建立的是大堆还是小堆,此处是小堆
        return (int)(this.time-o.time);
    }

}
class MyTimerClass {
    private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
    private Object locker=new Object();
    public MyTimerClass() {
        Thread t1=new Thread(()-> {
            try {
                while (true) {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
//                            continue;
                            //若队列为空,那么线程将拿着锁一直在循环转圈,而不执行任何操作,将消耗很多资源
                            locker.wait();
                        }
                        MyTimerTask current = queue.peek();
                        if (System.currentTimeMillis() >= current.getTime()) {
                            //要执行任务
                            current.run();
                            queue.poll();//把执行完的任务删除
                        } else {
//                            continue;
                            //不执行任务,若时间还没到,线程会反复检测,一直循环,加锁解锁...
                            //设置超时时间,从而避免反复循环的过程,wait的时候,线程阻塞,释放CPU资源
                            locker.wait(current.getTime()-System.currentTimeMillis());
                        }
                    }
                }
            }catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
    }
    //将任务提交到队列中
    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}

public class MyTimer {
    public static void main(String[] args) {
        MyTimerClass myTimerClass=new MyTimerClass();
        myTimerClass.schedule(()-> {
            System.out.println("hello 3000");
        },3000);

        myTimerClass.schedule(()-> {
            System.out.println("hello 2000");
        },2000);

        myTimerClass.schedule(()-> {
            System.out.println("hello 1000");
        },1000);
        System.out.println("程序开始执行");
    }
}
